/*
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
package com.tlr.device.rest;

import com.tfb.service.utility.JsonUtil;
import com.tlr.device.model.Alert;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;

@ServerEndpoint("/ebansocket")
public class EbanWebsocketService {

    private static final Logger log = Logger.getLogger(EbanWebsocketService.class);
    private static final Map<String, Session> idClients = Collections.synchronizedMap(new HashMap<String, Session>());

    @SuppressWarnings("LeakingThisInConstructor")
    public EbanWebsocketService() {
        log.info("eban web socket is loading");
        AppContext.setEbanSocketService(this);
    }

    @OnOpen
    public void onOpen(Session session) {
        // Add session to the connected sessions set
        idClients.put(session.getId(), session);
        log.info("Added an eban client: " + session.getId());
    }

    @OnMessage
    public String onMessage(String message, Session session) {
        return "OK";
    }

    @OnClose
    public void onClose(Session session) {
        // Remove session from the connected sessions set
        idClients.remove(session.getId());
        log.info("Removed an eban client: " + session.getId());
    }

    public void notifyMessage(Alert alert) {
        for (Entry<String, Session> client : idClients.entrySet()) {
            log.info("Eban session: " + client.getKey() + " is notified");
            client.getValue().getAsyncRemote().sendText(JsonUtil.writeValue(alert));
        }
    }

}
